<template>
  <div class="charts-container">
    <div class="header">
      <h2 class="title">欢迎使用健身管理系统</h2>
      <p class="subtitle">数据统计与分析中心</p>
    </div>

    <el-row :gutter="20">
      <!-- 热门课程图表 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="card-header">
              <i class="el-icon-star-on icon"></i>
              <span class="card-title">热门课程排行榜</span>
              <el-tag type="primary" size="small" class="tag">热度</el-tag>
            </div>
          </template>
          <div class="chart-wrapper">
            <bar-chart
                v-if="hotCourseDataLoaded"
                :data="hotCourseData"
                :options="hotCourseOptions"
                class="chart"
            />
            <div v-else class="loading">
              <div class="spinner"></div>
              <span class="loading-text">{{ hotCourseLoading ? '数据加载中...' : '暂无数据' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 课程评分图表 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="card-header">
              <i class="el-icon-medal icon"></i>
              <span class="card-title">课程评分排行榜</span>
              <el-tag type="success" size="small" class="tag">评分</el-tag>
            </div>
          </template>
          <div class="chart-wrapper">
            <bar-chart
                v-if="gradingDataLoaded"
                :data="gradingData"
                :options="gradingOptions"
                class="chart"
            />
            <div v-else class="loading">
              <div class="spinner"></div>
              <span class="loading-text">{{ gradingLoading ? '数据加载中...' : '暂无数据' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

// ... existing code ...
<script>
import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'
import { Bar } from 'vue-chartjs'
import {getJwt} from "@/api/jwt.js";
import axios from 'axios'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

export default {
  name: 'CourseCharts',
  components: {
    BarChart: Bar
  },
// ... existing code ...

  data() {
    return {
      // 热门课程数据
      hotCourseData: {
        labels: [],
        datasets: [
          {
            label: '预约次数',
            backgroundColor: 'rgba(64, 158, 255, 0.8)',
            borderColor: 'rgba(64, 158, 255, 1)',
            borderWidth: 1,
            borderRadius: 4,
            data: []
          }
        ]
      },
      hotCourseOptions: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            titleFont: {
              size: 13
            },
            bodyFont: {
              size: 12
            },
            padding: 8,
            callbacks: {
              label: function(context) {
                return `预约次数: ${context.parsed.y}`;
              }
            }
          }
        },
        scales: {
          x: {
            grid: {
              display: false
            },
            ticks: {
              font: {
                size: 11
              },
              autoSkip: false,
              maxRotation: 45,
              minRotation: 45
            }
          },
          y: {
            beginAtZero: true,
            ticks: {
              precision: 0,
              font: {
                size: 11
              }
            },
            grid: {
              color: 'rgba(0, 0, 0, 0.05)'
            }
          }
        },
        animation: {
          duration: 800,
          easing: 'easeOutQuart'
        }
      },
      hotCourseDataLoaded: false,
      hotCourseLoading: false,

      // 评分数据
      gradingData: {
        labels: [],
        datasets: [
          {
            label: '平均评分',
            backgroundColor: 'rgba(103, 194, 58, 0.8)',
            borderColor: 'rgba(103, 194, 58, 1)',
            borderWidth: 1,
            borderRadius: 4,
            data: []
          }
        ]
      },
      gradingOptions: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            titleFont: {
              size: 13
            },
            bodyFont: {
              size: 12
            },
            padding: 8,
            callbacks: {
              label: function(context) {
                return `平均评分: ${context.parsed.y} 分`;
              }
            }
          }
        },
        scales: {
          x: {
            grid: {
              display: false
            },
            ticks: {
              font: {
                size: 11
              },
              autoSkip: false,
              maxRotation: 45,
              minRotation: 45
            }
          },
          y: {
            beginAtZero: true,
            max: 5,
            ticks: {
              stepSize: 1,
              font: {
                size: 11
              }
            },
            grid: {
              color: 'rgba(0, 0, 0, 0.05)'
            }
          }
        },
        animation: {
          duration: 800,
          easing: 'easeOutQuart'
        }
      },
      gradingDataLoaded: false,
      gradingLoading: false
    }
  },
  mounted() {
    this.fetchHotCourseData()
    this.fetchGradingData()
  },
  methods: {
    // 通用的fetch方法
    async fetchData(url) {
      try {
        const response = await axios.get(url, {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `${getJwt()}`
          }
        });
        return response.data;
      } catch (error) {
        console.error('Axios error:', error);
        throw error;
      }
    },

    // 获取热门课程数据
    async fetchHotCourseData() {
      this.hotCourseLoading = true;
      try {
        const response = await this.fetchData('/api/charts/courseHotChart');
        if (response.code === 200) {
          const courseHots = response.data || [];
          const topCourses = courseHots.slice(0, 10);

          // 修正字段名：使用courseName和totalReservations
          this.hotCourseData.labels = topCourses.map(item => item.courseName);
          this.hotCourseData.datasets[0].data = topCourses.map(item => item.totalReservations);
          this.hotCourseDataLoaded = topCourses.length > 0;
        } else {
          this.$message.error(response.message || '获取热门课程数据失败');
          this.hotCourseDataLoaded = false;
        }
      } catch (error) {
        this.$message.error('获取热门课程数据时发生错误: ' + (error.message || '网络错误'));
        console.error(error);
        this.hotCourseDataLoaded = false;
      } finally {
        this.hotCourseLoading = false;
      }
    },

    // 获取课程评分数据
    async fetchGradingData() {
      this.gradingLoading = true;
      try {
        const response = await this.fetchData('/api/charts/courseGrading');
        if (response.code === 200) {
          const courseGradings = response.data || [];
          // 限制显示前10个评分课程
          const topGradings = courseGradings.slice(0, 10);

          // 修正字段名：使用courseName和averageScore
          this.gradingData.labels = topGradings.map(item => item.courseName);
          this.gradingData.datasets[0].data = topGradings.map(item => item.averageScore);
          this.gradingDataLoaded = topGradings.length > 0;
        } else {
          this.$message.error(response.message || '获取课程评分数据失败');
          this.gradingDataLoaded = false;
        }
      } catch (error) {
        this.$message.error('获取课程评分数据时发生错误: ' + (error.message || '网络错误'));
        console.error(error);
        this.gradingDataLoaded = false;
      } finally {
        this.gradingLoading = false;
      }
    }
  }
}
</script>

<style scoped>
.charts-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-bottom: 0;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

.chart-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
}

.icon {
  font-size: 18px;
  margin-right: 8px;
  color: #409eff;
}

.card-title {
  flex: 1;
  font-size: 16px;
  color: #303133;
}

.tag {
  margin-left: 10px;
}

.chart-wrapper {
  height: 380px;
  position: relative;
  padding: 15px;
}

.chart {
  width: 100%;
  height: 100%;
}

.loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(64, 158, 255, 0.2);
  border-top: 3px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 13px;
  color: #909399;
}

:deep(.el-card__header) {
  background-color: #fafbff;
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

:deep(.el-card__body) {
  padding: 0;
}

@media (max-width: 768px) {
  .charts-container {
    padding: 15px;
  }

  :deep(.el-col) {
    width: 100%;
    margin-bottom: 15px;
  }

  .title {
    font-size: 20px;
  }

  .chart-wrapper {
    height: 300px;
  }

  .header {
    padding: 15px;
  }
}
</style>
